#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;
using std::string;
using namespace ns_control;

static Control* pctrl = nullptr;

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " listen_port" << std::endl;

    exit(1);
}

/**
 * @brief 自定义信号处理函数，用于恢复所有离线服务器
 *
 * @param[in] signo 信号值
 *
 */
void recovery(int signo)
{
    pctrl->recover();
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
    }

    signal(SIGQUIT,recovery);
    /*  对用户的请求进行路由 */
    Server svr;
    Control ctrl;
    pctrl = &ctrl;

    svr.Get("/all_questions",[&ctrl](const Request& req,Response& resp){
        string html_content;
        ctrl.all_questions(&html_content);
        resp.set_content(html_content,"text/html; charset=utf-8");
    });

    svr.Get(R"(/question/(\d+))",[&ctrl](const Request& req,Response& resp){
        std::string number = req.matches[1];
        string html_content;
        ctrl.one_question(number,&html_content);
        resp.set_content(html_content,"text/html; charset=utf-8");
    });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string result_json;
        ctrl.judge(number,req.body,&result_json);
        resp.set_content(result_json, "text/plain; charset=utf-8");
    });

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", atoi(argv[1]));

    return 0;
}